<?php
namespace app\admin\logic;

use app\admin\logic\Index as IndexLogic;
use app\admin\model\Menu as MenuModel;
use app\admin\model\Module as ModuleModel;
use app\user\model\Role as RoleModel;

class Module
{
    public function update($name)
    {
        $Module = ModuleModel::where(['name' => $name])->find();

        // 添加菜单
        $menus = ModuleModel::getMenusFromFile($name);
        if (is_array($menus) && !empty($menus)) {
            $ids=$this->updateMenus($menus, $name);
            MenuModel::whereNotIn('id',$ids)->where('module',$name)->update(['status'=>0]);//重置所有菜单为不可用
        }

        // 模块配置信息
        $module_info = ModuleModel::getInfoFromFile($name);

        unset($module_info['name']);

        // 检查是否有模块设置信息
        if (isset($module_info['config']) && !empty($module_info['config'])) {
            $module_info['config'] = json_encode(parse_config($module_info['config']));
        } else {
            $module_info['config'] = '';
        }

        // 检查是否有模块授权配置
        if (isset($module_info['access']) && !empty($module_info['access'])) {
            $module_info['access'] = json_encode($module_info['access']);
        } else {
            $module_info['access'] = '';
        }

        $res=$Module->save($module_info);

        $wipe_cache_type = config('app.wipe_cache_type');
        if (!empty($wipe_cache_type)) {
            $IndexLogic = new IndexLogic();
            $IndexLogic->wipeCache($wipe_cache_type);
        }
        return $res;
    }

    /**
     * 更新模型菜单
     * @param array $menus 菜单
     * @param string $module 模型名称
     * @param int $pid 父级ID
     * @author rocky
     * @return bool
     */
    private function updateMenus($menus = [], $module = '', $pid = 0)
    {
        $ids=[];//处理的id集合
        foreach ($menus as $menu) {
            $menu['pid']=$pid;
            $menu['module']=$module;
            $ids[]=$id=MenuModel::insertOrupdate($menu);
            if($menu['role']??''){
                $roles=array_keys(array_flip(explode(',',$menu['role'])));
                $role = array_diff($roles,RoleModel::getRoleWithMenu($id));
                foreach ($role as $key => $roleid) {
                    $menu_auth = RoleModel::where('id', $roleid)->value('menu_auth');
                    $menu_auth = json_decode($menu_auth, true);
                    $menu_auth[]="$id";
                    RoleModel::where('id', $roleid)->update(['menu_auth'=>json_encode($menu_auth)]);
                }
            }

            if (isset($menu['child'])) {
                $ids=array_merge($ids,$this->updateMenus($menu['child'], $module, $id));
            }
        }
        return $ids;
    }

}
